<template>
    <div>
<!--        面包屑-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/goods">商品管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
<!--        卡片区-->
        <el-card>
<!--            提示-->
            <el-alert
                    show-icon
                    :closable="false"
                    title="注意只能为第三级分类设置参数"
                    type="warning">
            </el-alert>
            <el-row style="margin:5px">
                <el-col :span="2" style="display: flex;align-items: center">
                    选择商品分类：
                </el-col>
                <el-col :span="3">
                    <el-cascader
                            :options="categories"
                            :props="cascaderConfig"
                            @change="handleChange"></el-cascader>
                </el-col>
            </el-row>
<!--            参数-->
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-row style="margin:5px">
                        <el-col :span="2">
                            <el-button type="primary" :disabled="!selectedId" @click="showAddAttributeDialog">添加参数</el-button>
                        </el-col>
                    </el-row>
<!--                    列表-->
                    <el-table :data="manyAttributeList"
                              default-expand-all
                              border stripe>
                        <el-table-column type="expand">
                            <template #default="scope">
                                <el-tag v-for="(item,index) in scope.row.attr_vals"
                                        closable
                                        @close="removeAttribute(scope.row,index)"
                                        :key="index">{{item}}</el-tag>
<!--                                新增属性-->
                                <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button size="mini"
                                           type="primary"
                                           @click="showEditAttributeDialog(scope.row.attr_id)"
                                           icon="el-icon-edit">编辑</el-button>
                                <el-button size="mini"
                                           type="danger"
                                           @click="deleteAttribute(scope.row.attr_id)"
                                           icon="el-icon-delete">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-row style="margin:5px">
                        <el-col :span="2">
                            <el-button type="primary" :disabled="!selectedId" @click="showAddAttributeDialog">添加属性</el-button>
                        </el-col>
                    </el-row>
                    <el-table :data="onlyAttributeList"
                              default-expand-all
                              border stripe>
                        <el-table-column type="expand">
                            <template #default="scope">
                                <el-tag v-for="(item,index) in scope.row.attr_vals"
                                        closable
                                        @close="removeAttribute(scope.row,index)"
                                        :key="index">{{item}}</el-tag>
                                <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button size="mini"
                                           type="primary"
                                           @click="showEditAttributeDialog(scope.row.attr_id)"
                                           icon="el-icon-edit">编辑</el-button>
                                <el-button size="mini"
                                           type="danger"
                                           @click="deleteAttribute(scope.row.attr_id)"
                                           icon="el-icon-delete">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
<!--            添加属性dialog-->
            <el-dialog :title="'添加'+activeTitle"
                       v-model="addAttributeDialogVisible"
                       @close="closeAddAttributeDialog"
                       width="40%">
                <el-form :model="addAttributeForm"
                         :rules="addAttributeFormRules"
                         ref="addAttributeFormRef"
                         label-width="120px"
                         class="demo-ruleForm">
                    <el-form-item :label="activeTitle+':'" prop="attr_name">
                        <el-input v-model="addAttributeForm.attr_name"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <el-button @click="closeAddAttributeDialog">取消</el-button>
                    <el-button type="primary" @click="addAttribute">确定</el-button>
                </template>
            </el-dialog>
<!--            修改属性dialog-->
            <el-dialog :title="'修改'+activeTitle"
                       v-model="editAttributeDialogVisible"
                       @close="closeEditAttributeDialog"
                       width="40%">
                <el-form :model="editAttributeForm"
                         :rules="editAttributeFormRules"
                         ref="editAttributeFormRef"
                         label-width="120px"
                         class="demo-ruleForm">
                    <el-form-item :label="'新'+activeTitle+':'" prop="attr_name">
                        <el-input v-model="editAttributeForm.attr_name"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <el-button @click="closeEditAttributeDialog">取消</el-button>
                    <el-button type="primary" @click="editAttribute">确定</el-button>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
  export default {
    name: "Parameters",
    data(){
      return {
        categories:[],//分类列表
        selectedId:null,//选中的分类
        cascaderConfig:{//级联选择器配置项
          label:'cat_name',
          value:'cat_id'
        },
        activeName:'many',//被激活的tab

        manyAttributeList:[],//动态参数列表
        onlyAttributeList:[],//静态属性列表
        addAttributeDialogVisible:false,//添加属性dialog,
        addAttributeForm:{
          attr_name:'',//属性名
        },
        addAttributeFormRules:{
          attr_name:[{required:true,message:'请输入属性名',trigger:'blur'}]
        },
        editAttributeDialogVisible:false,//编辑dialog
        editAttributeForm:{
          attr_name:'',
        },
        editAttributeFormRules:{
          attr_name:[{required: true,message:'请输入新的属性名',trigger:'blur'}]
        },
        inputManyVisible:false,//添加动态参数
        inputManyValue:'',//动态新增属性值

      }
    },
    computed:{
      activeTitle(){
        return this.activeName==='many'? '动态参数':'静态属性'
      }
    },
    created() {
      this.getCategories();
    },
    methods:{
      //获取分类列表
      async getCategories(){
        const {data:res} = await this.$http.get(`/categories`);
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }
        this.categories = res.data;
      },
      handleChange(val){
        this.selectedId = val[2];
        this.getAttributeList();
      },
      //点击tab
      handleClick(){
        console.log(this.activeName);
        if(this.selectedId){
          this.getAttributeList();
        }
      },
      //获取参数列表
      async getAttributeList(){
        const {data:res}  = await this.$http.get(`/categories/${this.selectedId}/attributes?sel=${this.activeName}`,);
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }
        //将每个属性值分割为数组
        res.data.forEach(item=>{
          item.attr_vals = (item.attr_vals? item.attr_vals.split(' '):[]);
          //为每一行提供一个inputVisible和inputValue用于新增属性
          item.inputVisible = false;
          item.inputValue = '';
        })

        this.$message.success(res.meta.msg);
        if(this.activeName === 'many'){
          this.manyAttributeList = res.data;
        }else{
          this.onlyAttributeList = res.data;
        }
        //console.log(res.data);
      },
      showAddAttributeDialog(){
        this.addAttributeDialogVisible = true;
      },
      closeAddAttributeDialog(){
        this.$refs.addAttributeFormRef.resetFields();
        this.addAttributeDialogVisible = false;
      },
      //添加属性
      addAttribute(){
        this.$refs.addAttributeFormRef.validate(async valid=>{
          if(valid){
            const {data:res} = await this.$http.post(`categories/${this.selectedId}/attributes`,{
              attr_name:this.addAttributeForm.attr_name,
              attr_sel:this.activeName,
            })
            if(res.meta.status !== 201){
              return this.$message.error(res.meta.msg);
            }else{
              this.$message.success(res.meta.msg);
              this.getAttributeList();
              this.closeAddAttributeDialog();
            }
          }else{
            return
          }
        })
      },
      //修改属性的dialog
      showEditAttributeDialog(id){
        this.editId = id;
        this.getAttributeInfoById(id);
        this.editAttributeDialogVisible = true;
      },
      closeEditAttributeDialog(){
        this.editId = null;
        this.$refs.editAttributeFormRef.resetFields();
        this.editAttributeDialogVisible = false;
      },
      //根据id查询参数信息
      async getAttributeInfoById(id){
        const {data:res} = await  this.$http.get(`categories/${this.selectedId}/attributes/${id}`);
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }
        this.editAttributeForm = res.data;
      },
      //修改参数
      async editAttribute(){
        const {data:res} = await this.$http.put(`categories/${this.selectedId}/attributes/${this.editId}`,{
          attr_name:this.editAttributeForm.attr_name,
          attr_sel:this.activeName,
        })
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }
        this.$message.success(res.meta.msg);
        this.closeEditAttributeDialog();
        this.getAttributeList();
      },
      //删除属性
      async deleteAttribute(id){
        const res1 = await this.$confirm('是否删除此属性？','提示',{
          confirmButtonText:'确定',
          cancelButtonText:'取消',
          type:'warning',
        }).catch(err=>console.log(err));
        if(res1 !== 'confirm'){
          return this.$message.info('用户取消操作');
        }
        const {data:res} = await this.$http.delete(`categories/${this.selectedId}/attributes/${id}`);
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }
        this.$message.success(res.meta.msg);
        this.getAttributeList();
      },
      //文本框失去焦点或者按下enter
      async handleInputConfirm(row){
        //console.log('ok');
        if(row.inputValue.trim().length===0){
          row.inputValue = '';
          row.inputVisible = false;
          return
        }
        row.attr_vals.push(row.inputValue);
        //保存到数据库
        const {data:res} = await this.$http.put(`categories/${this.selectedId}/attributes/${row.attr_id}`,{
          attr_name:row.attr_name,
          attr_sel:row.attr_sel,
          attr_vals:row.attr_vals.join(' '),
        })
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }
        this.$message.success('添加成功')
        row.inputValue = ''
        row.inputVisible = false;
        //row.inputManyValue = ''
      },
      //删除属性项
      async removeAttribute(row,index){
        row.attr_vals.splice(index,1);
        const {data:res} = await this.$http.put(`categories/${this.selectedId}/attributes/${row.attr_id}`,{
          attr_name:row.attr_name,
          attr_sel:row.attr_sel,
          attr_vals:row.attr_vals.join(' '),
        })
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }
        this.$message.success('移除成功')
      },
      //展示文本输入框
      showInput(row){
        row.inputVisible = true;
        //页面重新被渲染之后才会调用this.$nextTick
        this.$nextTick(_ => {
          //让输入框自动获取焦点
          this.$nextTick(_ => {
            this.$refs.saveTagInput.$refs.input.focus();
          });
        });
      }
    }
  }
</script>

<style scoped>
    .el-tag + .el-tag {
        margin-left: 10px;
    }
    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }
    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }
</style>
